package com.develop.mybluetooth.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseMultiItemAdapter
import com.develop.mybluetooth.bean.BMessage
import com.develop.mybluetooth.databinding.ItemMessageReceivedBinding
import com.develop.mybluetooth.databinding.ItemMessageSentBinding

class MessageAdapter :  BaseMultiItemAdapter<BMessage>() {


    fun addMessage(bMessage: BMessage) {
        add(itemCount, bMessage)
    }

    init {
        addItemType(TYPE_SENT, object : OnMultiItemAdapterListener<BMessage, SentMessageHolder> { // 类型 1
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): SentMessageHolder {
                // 创建 viewholder
                val viewBinding = ItemMessageSentBinding.inflate(LayoutInflater.from(context), parent, false)
                return SentMessageHolder(viewBinding)
            }

            override fun onBind(holder: SentMessageHolder, position: Int, item: BMessage?) {
                // 绑定 item 数据
                holder.tvContent.text = item?.content
                holder.tvTime.text = item?.timestamp
            }
        }).addItemType(TYPE_RECEIVED, object : OnMultiItemAdapterListener<BMessage, ReceivedMessageHolder> { // 类型 2
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ReceivedMessageHolder {
                // 创建 viewholder
                val viewBinding = ItemMessageReceivedBinding.inflate(LayoutInflater.from(context), parent, false)
                return ReceivedMessageHolder(viewBinding)
            }

            override fun onBind(holder: ReceivedMessageHolder, position: Int, item: BMessage?) {
                // 绑定 item 数据
                holder.tvContent.text = item?.content
                holder.tvTime.text = item?.timestamp
            }

            override fun isFullSpanItem(itemType: Int): Boolean {
                // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                return true;
            }

        }).onItemViewType { position, list -> // 根据数据，返回对应的 ItemViewType
            if (list[position].isSent) {
                TYPE_SENT
            } else {
                TYPE_RECEIVED
            }
        }
    }

    companion object {
        private const val TYPE_SENT = 0
        private const val TYPE_RECEIVED = 1
    }


    internal class SentMessageHolder(binding: ItemMessageSentBinding) : RecyclerView.ViewHolder(binding.root){
        val tvContent = binding.tvContent
        val tvTime = binding.tvTime
    }
    internal class ReceivedMessageHolder(binding: ItemMessageReceivedBinding) : RecyclerView.ViewHolder(binding.root){
        val tvContent = binding.tvContent
        val tvTime = binding.tvTime
    }


}
